package com.hrt.common.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.btcode.orm.conver.DefaultModelConver;
import com.btcode.orm.conver.IModelConver;
import com.btcode.orm.model.IField;
import com.btcode.orm.model.IModel;

public class DSRequestUnit extends com.btcode.web.core.unit.RequestUnit {

    public static <T extends IModel> T getModel(Class<T> modelClass) {

        HashMap<String, Object> value = getHashMapParmO();

        IModelConver modelConver = new DefaultModelConver();
        T model = modelConver.converORMModelHashMap(value, modelClass);

        return model;
    }

    public static <T extends IModel> List<T> getModels(Class<T> modelClass) {

        List<T> models = new ArrayList<>();

        HashMap<String, Object> paramO = getHashMapParmO();

        T modelTemp;

        try {
            modelTemp = modelClass.newInstance();
        } 
        catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }

        IModelConver modelConver = new DefaultModelConver();

        List<IField> fields = modelTemp.getFields();

        int index = 0;

        while (true) {
            HashMap<String, Object> item = new HashMap<>();
            boolean hasValue = false;

            for (IField field : fields) {
                Object v = paramO.get("data[" + index + "][" + field.getFieldName() + "]");
                item.put(field.getFieldName(), v);
                if (v != null) {
                    hasValue = true;
                }
            }

            if (hasValue) {
                T model = modelConver.converORMModelHashMap(item, modelClass);
                models.add(model);
            }
            else {
                break;
            }

            index++;
        }

        return models;
    }

}
